package com.dyz.leetcode._09_heapAndPriorityQueue;

import java.util.HashMap;
import java.util.PriorityQueue;

public class _347_topKFrequent {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>(k+1, (a, b)->map.get(a)-map.get(b));

        for(int num:map.keySet()){
            pq.add(num);
            if(pq.size()>k){
                pq.remove();
            }
        }

       int [] ans = new int[k];
        int size = 0;
        while (!pq.isEmpty()){
            ans[size++] = pq.remove();
        }
    return ans;
    }
}
